<template>
  <div class="track_the_playback">
    <div class="around">
      <!-- 设置时间 -->
      <i class="el-icon-time" title="设置时间段" @click="setTime.show = true">设置时间段</i>
      <!-- 数据列表 -->
      <i class="el-icon-s-operation" title="打开数据列表" @click="openDataList">打开数据列表</i>
      <!-- 开始播放 -->
      <i class="el-icon-kaishi" title="开始播放" @click="start">开始播放</i>
      <!-- 停止播放 -->
      <i class="el-icon-tingzhi" title="停止播放" @click="stop">停止播放</i>
      <!-- 设置速度 -->
      <i class="el-icon-speed" title="设置播放速度" @click="speed.show = true">设置播放速度</i>
      <!-- 设置播放间隔步数 -->
      <i class="el-icon-bushu" title="设置播放间隔" @click="step.show = true">设置播放间隔</i>
      <!-- 清除轨迹 -->
      <i class="el-icon-qingchu" title="清除轨迹" @click="clear">清除轨迹</i>
    </div>
    <!-- 地图 -->
    <div class="container">
      <div id="map"></div>
    </div>
    <div class="around"></div>
    <!-- 数据列表 -->
    <el-dialog title="车辆轨迹点详情" :visible.sync="dataListDialog" width="49%" class="dialogchild">
      <el-form class="dialogform">
        <table style="width:100%;text-align:center;border-collapse:collapse" class="tables">
          <tbody>
            <tr>
              <th>经度</th>
              <th>纬度</th>
              <th>速度</th>
              <th>方向</th>
              <th>定位时间</th>
            </tr>
            <tr v-for="item in dataList" :key="item.VehicleName">
              <td>{{item.Lng}}</td>
              <td>{{item.Lat}}</td>
              <td>{{item.Speed}}</td>
              <td>{{item.Direction}}</td>
              <td>{{item.GpsTime}}</td>
            </tr>
          </tbody>
        </table>
      </el-form>
    </el-dialog>
    <div class="set_time_box" v-if="setTime.show">
      <h2>
        <span>设置时间段</span>
        <i class="iconfont icon-guanbi" @click="setTime.show = false"></i>
      </h2>
      <div class="content">
        <div>
          <span>开始时间</span>
          <el-date-picker
            v-model="setTime.startTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </div>
        <div>
          <span>结束时间</span>
          <el-date-picker
            v-model="setTime.endTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </div>
        <div>
          <el-button type="primary" @click="getDataList">确 定</el-button>
        </div>
      </div>
    </div>
    <!-- 速度条 -->
    <div class="speed" v-if="speed.show">
      <h2>
        <span>设置播放速度</span>
        <i class="iconfont icon-guanbi" @click="speed.show = false"></i>
      </h2>
      <el-slider v-model="speed.value" :step=".1" :max="2" :min=".1" :format-tooltip="formatSpeed"></el-slider>
      <el-button type="primary" @click="speed.show = false">确 定</el-button>
    </div>
    <!-- 设置播放间隔 -->
    <div class="speed" v-if="step.show">
      <h2>
        <span>设置播放间隔</span>
        <i class="iconfont icon-guanbi" @click="step.show = false"></i>
      </h2>
      <el-slider v-model="step.value" :step="1" :max="20" :min="1"></el-slider>
      <el-button type="primary" @click="step.show = false">确 定</el-button>
    </div>
    <div class="map_select" style="right: 25px;height: 185px">
        <p>
          <input id="checkbox_village" type="checkbox" @click="handleCheckVillage" />
          <span>小区垃圾点</span>
        </p>
        <p>
          <input id="checkbox_restaurant" type="checkbox" @click="handleCheckRestaurant" />
          <span>餐饮单位</span>
        </p>
        <p>
          <input id="checkbox_restaurant2" type="checkbox" @click="handleCheckRestaurant2" />
          <span>沿街小饭店</span>
        </p>
        <p>
          <input id="checkbox_clc" type="checkbox" checked @click="handleCheckCLC" />
          <span>处理厂</span>
        </p>
        <p>
          <input id="checkbox_zzz" type="checkbox" @click="handleCheckZZZ" />
          <span>中转站</span>
        </p>
      </div>
  </div>
</template>

<script>
import DirectionImg from '@/assets/images/direction.png'
import imgMarkerCLC from '@/assets/images/marker/markerImageCLC.png'
import imgMarkerRestaurant from '@/assets/images/marker/markerImageRestaurant.png'
import imgMarkerRestaurant2 from '@/assets/images/marker/markerImageRestaurant2.png'
import imgMarkerVillage from '@/assets/images/marker/markerImageVillage.png'
import imgMarkerZZZ from '@/assets/images/marker/markerImageZZZ.png'
export default {
  data () {
    function timeDefault (isEarlier) {
      // var _this = this;
      const yy = new Date().getFullYear()
      const mm = new Date().getMonth() + 1
      const dd = new Date().getDate()
      let hh = new Date().getHours()
      if (isEarlier) {
        hh = new Date().getHours() - 1
      }
      const mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
      const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
      return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
    }
    return {
      map: null,
      dataListDialog: false,
      dataList: [],
      dataCurrentIndex: 0,
      ary: [],
      VID: 0,
      setTime: {
        show: true,
        startTime: timeDefault(true),
        endTime: timeDefault(false)
        // startTime: '2020-04-02 07:05:00',
        // endTime: '2020-04-02 07:11:00'
      },
      timeId: null,
      // 速度
      speed: {
        show: false,
        value: 0.2
      },
      // 步数
      step: {
        show: false,
        value: 1
      },
      markerARR_Restaurant: [],
      markerARR_Restaurant2: [],
      markerARR_Village: [],
      markerARR_CLC: [],
      markerARR_ZZZ: []
    }
  },
  created () {
    // const _this = this
    const date = new Date().toLocaleDateString()
    const date2 = new Date().toTimeString()
    console.log(date, date2)

    this.VID = this.$route.params.VID
  },
  methods: {
    // 显示地图
    mapShow () {
      // 百度地图API功能
      this.map = new BMap.Map('map')// 创建Map实例
      this.map.centerAndZoom(new BMap.Point(117.2, 39.15), 16)// 初始化地图,设置中心点坐标和地图级别
      this.map.setCurrentCity('天津市')// 设置地图显示的城市 此项是必须设置的
      // 开启滚轮缩放
      this.map.enableScrollWheelZoom(true)
    },
    // 轨迹回放画线
    async playTrack () {
      const data = this.dataList
      // 以第一个坐标点为地图中心点
      this.map.centerAndZoom(new BMap.Point(data[0].Lng, data[0].Lat), 16)
      const _this = this

      // 定时画线
      this.timeId = setInterval(() => {
        // 清除定时器，停止画线
        if (this.dataCurrentIndex === data.length - 1) {
          this.stop()
          this.dataCurrentIndex = 0
          return true
        }
        // 上一个点
        this.dataCurrentIndex = this.dataCurrentIndex + this.step.value
        const prevPoint = this.dataCurrentIndex - this.step.value
        add(data[prevPoint])

        console.log('aa', this.dataCurrentIndex)
        // 下一个点
        this.createPoint(data[prevPoint].Lng, data[prevPoint].Lat, data[this.dataCurrentIndex].Lng, data[this.dataCurrentIndex].Lat)
      }, 1000 * this.speed.value)
      // })
      // 画线
      function add (point) {
        _this.ary.push(new BMap.Point(point.Lng, point.Lat))
        const polyline = new BMap.Polyline(_this.ary, { strokeColor: 'blue', strokeWeight: 3, strokeOpacity: 1 })
        _this.map.addOverlay(polyline)
      }
    },
    // 创建标记点
    createPoint (lng1, lat1, lng2, lat2) {
      // 获取两个标记点的角度
      const k = this.getAngle(lng1, lat1, lng2, lat2)
      // 创建标记点
      const pt = new BMap.Point(lng1, lat1)
      // 标记点图片
      const myIcon = new BMap.Icon(DirectionImg, new BMap.Size(20, 26))
      // 添加图片
      const marker = new BMap.Marker(pt, { icon: myIcon })
      // 设置标记点方向
      marker.setRotation(k)
      // 将标注添加到地图中
      this.map.addOverlay(marker)
      // 如果点位在当前地图显示范围外，则将该点设置为地图中心
      if (!this.map.getBounds().containsPoint(pt)) {
        this.map.centerAndZoom(pt, 16)
      }
    },
    // 获取两个点的角度
    getAngle (lng1, lat1, lng2, lat2) {
      const a = (90 - lat2) * Math.PI / 180
      const b = (90 - lat1) * Math.PI / 180
      const AOC_BOC = (lng2 - lng1) * Math.PI / 180
      const cosc = Math.cos(a) * Math.cos(b) + Math.sin(a) * Math.sin(b) * Math.cos(AOC_BOC)
      const sinc = Math.sqrt(1 - cosc * cosc)
      const sinA = Math.sin(a) * Math.sin(AOC_BOC) / sinc
      const A = Math.asin(sinA) * 180 / Math.PI
      let res = 0
      if (lng2 > lng1 && lat2 > lat1) res = A
      else if (lng2 > lng1 && lat2 < lat1) res = 180 - A
      else if (lng2 < lng1 && lat2 < lat1) res = 180 - A
      else if (lng2 < lng1 && lat2 > lat1) res = 360 + A
      else if (lng2 > lng1 && lat2 === lat1) res = 90
      else if (lng2 < lng1 && lat2 === lat1) res = 270
      else if (lng2 === lng1 && lat2 > lat1) res = 0
      else if (lng2 === lng1 && lat2 < lat1) res = 180
      return res
    },
    // 打开数据列表
    openDataList () {
      this.dataListDialog = true
      // this.getDataList()
    },
    // 选定时间段,获取数据列表
    async getDataList () {
      const { startTime, endTime } = this.setTime
      if (startTime === '' || endTime === '') {
        this.$message({
          message: '开始时间和结束时间不能为空！！！',
          type: 'warning'
        })
        return false
      }
      const params = {
        VID: this.VID,
        startTime,
        endTime
      }
      console.log(params)

      // 设置加载效果
      const loading = this.$loading({
        lock: true,
        text: '数据加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      const { data } = await this.$axios.get('http://111.160.78.62:9930/Cityscapeapi/DataListCompany/GetVehicleHistoryInfoListApi', { params })
      this.dataList = data
      loading.close()
      this.setTime.show = false
      // this.dataListDialog = true
    },
    // 格式化定位时间
    formatterTime (row) {
      return row.ORIENTATION_TIME.replace('T', ' ')
    },
    // 开始播放
    start () {
      this.dataListDialog = false
      if (this.dataCurrentIndex === 0) {
        this.clear()
      }
      this.playTrack()
    },
    // 停止播放
    stop () {
      clearTimeout(this.timeId)
    },
    // 格式化播放间隔
    formatSpeed (val) {
      return val + ' 秒播放一步'
    },
    // 清除轨迹
    clear () {
      this.stop()
      this.ary = []
      this.map.clearOverlays()
    },
    // 获取处理厂列表
    async getClcList () {
      const { data } = await this.$axios.get('http://111.160.78.62:9930/Cityscapeapi/DataListCompany/GetFactoryInfoApi?Type=1')
      this.clcList = data.filter(item => {
        return item
      })
      this.handleCheckCLC()
    },
    handleCheckCLC () {
      if (document.getElementById('checkbox_clc').checked) {
        // var bounds = this.map.getBounds()
        // var sw = bounds.getSouthWest()
        // var ne = bounds.getNorthEast()
        // var lngSpan = Math.abs(sw.lng - ne.lng)
        // var latSpan = Math.abs(ne.lat - sw.lat)
        // for (var j = 0; j < 25; j++) {
        //   var point = new BMap.Point(sw.lng + lngSpan * (Math.random() * 0.7), ne.lat - latSpan * (Math.random() * 0.7))
        //   var markerImage = new BMap.Icon(imgMarkerCLC, new BMap.Size(50, 50))
        //   var marker = new BMap.Marker(point, { icon: markerImage })
        //   marker.disableMassClear()
        //   this.map.addOverlay(marker)
        //   this.markerARR_CLC.push(marker)
        // }
        // var arr = [{ No: '1', Name: '天津碧海环保垃圾处理厂', Type: '边界点', LONGITUDE: '117.426409', LATITUDE: '38.872884' }, { No: '2', Name: '天津滨海新区垃圾焚烧发电厂', Type: '边界点', LONGITUDE: '117.725846', LATITUDE: '39.179505' }, { No: '3', Name: '天津滨海新区第二垃圾焚烧发电厂', Type: '边界点', LONGITUDE: '117.554278', LATITUDE: '38.786418' }, { No: '4', Name: '天津市双口生活垃圾卫生填埋场', Type: '边界点', LONGITUDE: '116.993805', LATITUDE: '39.236384' }]
        var pointPolygon = []
        for (var j = 0; j < this.clcList.length; j++) {
          var point = new BMap.Point(this.clcList[j].LONGITUDE, this.clcList[j].LATITUDE)
          pointPolygon.push(point)
        }
        // var polygon = new BMap.Polygon([new BMap.Point(117.425438, 38.872788), new BMap.Point(117.426718, 38.873610), new BMap.Point(117.427381, 38.872967), new BMap.Point(117.426111, 38.872155), new BMap.Point(117.425438, 38.872788)], { strokeColor: 'blue', strokeWeight: 2, strokeOpacity: 0.5 })
        var polygon = new BMap.Polygon(pointPolygon)
        polygon.disableMassClear()
        this.map.addOverlay(polygon)
        this.markerARR_CLC.push(polygon)
        var polygonCenter = polygon.getBounds().getCenter()
        var markerImage = new BMap.Icon(imgMarkerCLC, new BMap.Size(50, 50))
        var marker = new BMap.Marker(polygonCenter, { icon: markerImage })
        marker.disableMassClear()
        var label = new BMap.Label('天津碧海环保垃圾处理厂', { offset: new BMap.Size(-10, 50) })
        marker.setLabel(label)
        this.map.addOverlay(marker)
        this.markerARR_CLC.push(marker)
        this.map.centerAndZoom(polygonCenter, 16)
      } else {
        for (var i = 0; i < this.markerARR_CLC.length; i++) {
          this.markerARR_CLC[i].enableMassClear()
          this.map.removeOverlay(this.markerARR_CLC[i])
        }
        this.markerARR_CLC = []
      }
    },
    handleCheckZZZ () {
      if (document.getElementById('checkbox_zzz').checked) {
        var bounds = this.map.getBounds()
        var sw = bounds.getSouthWest()
        var ne = bounds.getNorthEast()
        var lngSpan = Math.abs(sw.lng - ne.lng)
        var latSpan = Math.abs(ne.lat - sw.lat)
        for (var j = 0; j < 25; j++) {
          var point = new BMap.Point(sw.lng + lngSpan * (Math.random() * 0.7), ne.lat - latSpan * (Math.random() * 0.7))
          var markerImage = new BMap.Icon(imgMarkerZZZ, new BMap.Size(50, 50))
          var marker = new BMap.Marker(point, { icon: markerImage })
          marker.disableMassClear()
          this.map.addOverlay(marker)
          this.markerARR_ZZZ.push(marker)
        }
      } else {
        for (var i = 0; i < this.markerARR_ZZZ.length; i++) {
          this.markerARR_ZZZ[i].enableMassClear()
          this.map.removeOverlay(this.markerARR_ZZZ[i])
        }
        this.markerARR_ZZZ = []
      }
    },
    handleCheckRestaurant () {
      if (document.getElementById('checkbox_restaurant').checked) {
        var bounds = this.map.getBounds()
        var sw = bounds.getSouthWest()
        var ne = bounds.getNorthEast()
        var lngSpan = Math.abs(sw.lng - ne.lng)
        var latSpan = Math.abs(ne.lat - sw.lat)
        for (var j = 0; j < 25; j++) {
          var point = new BMap.Point(sw.lng + lngSpan * (Math.random() * 0.7), ne.lat - latSpan * (Math.random() * 0.7))
          var markerImage = new BMap.Icon(imgMarkerRestaurant, new BMap.Size(50, 50))
          var marker = new BMap.Marker(point, { icon: markerImage })
          marker.disableMassClear()
          this.map.addOverlay(marker)
          this.markerARR_Restaurant.push(marker)
        }
      } else {
        for (var i = 0; i < this.markerARR_Restaurant.length; i++) {
          this.markerARR_Restaurant[i].enableMassClear()
          this.map.removeOverlay(this.markerARR_Restaurant[i])
        }
        this.markerARR_Restaurant = []
      }
    },
    handleCheckRestaurant2 () {
      if (document.getElementById('checkbox_restaurant2').checked) {
        var bounds = this.map.getBounds()
        var sw = bounds.getSouthWest()
        var ne = bounds.getNorthEast()
        var lngSpan = Math.abs(sw.lng - ne.lng)
        var latSpan = Math.abs(ne.lat - sw.lat)
        for (var j = 0; j < 25; j++) {
          var point = new BMap.Point(sw.lng + lngSpan * (Math.random() * 0.7), ne.lat - latSpan * (Math.random() * 0.7))
          var markerImage = new BMap.Icon(imgMarkerRestaurant2, new BMap.Size(50, 50))
          var marker = new BMap.Marker(point, { icon: markerImage })
          marker.disableMassClear()
          this.map.addOverlay(marker)
          this.markerARR_Restaurant2.push(marker)
        }
      } else {
        for (var i = 0; i < this.markerARR_Restaurant2.length; i++) {
          this.markerARR_Restaurant2[i].enableMassClear()
          this.map.removeOverlay(this.markerARR_Restaurant2[i])
        }
        this.markerARR_Restaurant2 = []
      }
    },
    handleCheckVillage () {
      if (document.getElementById('checkbox_village').checked) {
        var bounds = this.map.getBounds()
        var sw = bounds.getSouthWest()
        var ne = bounds.getNorthEast()
        var lngSpan = Math.abs(sw.lng - ne.lng)
        var latSpan = Math.abs(ne.lat - sw.lat)
        for (var j = 0; j < 25; j++) {
          var point = new BMap.Point(sw.lng + lngSpan * (Math.random() * 0.7), ne.lat - latSpan * (Math.random() * 0.7))
          var markerImage = new BMap.Icon(imgMarkerVillage, new BMap.Size(50, 50))
          var marker = new BMap.Marker(point, { icon: markerImage })
          marker.disableMassClear()
          this.map.addOverlay(marker)
          this.markerARR_Village.push(marker)
        }
      } else {
        for (var i = 0; i < this.markerARR_Village.length; i++) {
          this.markerARR_Village[i].enableMassClear()
          this.map.removeOverlay(this.markerARR_Village[i])
        }
        this.markerARR_Village = []
      }
    }
  },
  mounted () {
    // 显示地图
    this.mapShow()
    this.getClcList()
    // 画线
    // setTimeout(() => {
    //   this.addLine()
    // }, 2000)
  }
}
</script>

<style scoped lang="less">
/deep/.BMap_cpyCtrl {
  display: none !important;
}
/deep/.anchorBL {
  display: none !important;
}
.track_the_playback {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .around {
    height: 25px;
    background-color: #2ea9fa;
    &:first-child {
      padding-left: 10px;
      height: 30px;
      // line-height: 30px;
      i {
        color: #fff;
        font-size: 18px;
        font-weight: bold;
        //width: 30px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        margin-right: 15px;
      }
      // .el-icon-s-operation {
      //   font-size: 22px;
      // }
    }
  }
  .container {
    flex: 1;
    #map {
      height: 100%;
    }
  }
}
h2 {
  font-size: 16px;
  height: 30px;
  line-height: 30px;
  padding-left: 15px;
  border-bottom: 2px solid #ccc;
  background-color: #f1f1f1;
  i {
    float: right;
    margin-right: 10px;
  }
}
.content {
  height: calc(~'100% - 32px');
}
.data_list {
  height: 485px;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  box-shadow: 0 0 5px 3px #ccc;
  border-radius: 8px;
  overflow: hidden;
}
.set_time_box {
  width: 300px;
  height: 130px;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 4px;
  box-shadow: 0 0 5px 3px #ccc;
  background-color: #fff;
  h2 {
    border-bottom: 1px solid #ccc;
  }
  .content {
    padding-top: 5px;
    & > div {
      height: 26px;
      line-height: 26px;
      margin-bottom: 5px;
      padding-left: 20px;
      & > span {
        padding-right: 15px;
      }
      & > .el-button {
        float: right;
        padding: 0 5px;
        margin-right: 10px;
        height: 26px;
      }
    }
    /deep/.el-date-editor.el-input {
      width: 190px;
    }
    /deep/.el-input--prefix .el-input__inner {
      height: 26px;
      border-radius: 2px;
      padding: 0;
      padding-left: 5px;
      overflow: hidden;
      border-color: #3baefa;
      padding: 0;
      padding-left: 20px;
    }
    /deep/.el-input__icon {
      line-height: 26px;
    }
    /deep/.el-input__prefix {
      left: -1px;
    }
  }
}
.speed {
  width: 300px;
  height: 120px;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 0 5px 3px #ccc;
  background-color: #fff;
  .el-slider {
    margin: 10px 15px 0px;
    padding: 0 10px;
  }
  .el-button {
    float: right;
    margin-right: 15px;
    padding: 0 5px;
    height: 26px;
  }
}
</style>
